﻿using System;
using System.IO;

namespace YG.CommonFuncs
{
    /// <summary>
    /// 文件和路径操作
    /// </summary>
    public class FileAction
    {
        /// <summary>
        /// 判断文件夹是否存在，不存在就创建
        /// </summary>
        /// <param name="Path"></param>
        /// <returns></returns>
        public static bool FindPathAndCreate(string Path)
        {
            try
            {
                if (!Directory.Exists(Path))
                {
                    Directory.CreateDirectory(Path);
                }

                return true;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return false;
            }
        }

        /// <summary>
        /// 判断文件夹是否存在
        /// </summary>
        /// <param name="Path"></param>
        /// <returns></returns>
        public static bool FindPath(string Path)
        {
            try
            {
                if (!Directory.Exists(Path))
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return false;
            }
        }

        /// <summary>
        /// 判断文件是否存在
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static bool FindFile(string file)
        {
            try
            {
                if (File.Exists(file))
                {
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return false;
            }
        }

        /// <summary>
        /// 判断文件是否存在
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static bool DeleteFile(string file)
        {
            try
            {
                File.Delete(file);
                return true;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return false;
            }
        }

        public static bool IsFileInUse(string fileName)
        {
            bool inUse = true;
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
                inUse = false;
            }
            catch
            {
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
            return inUse;//true表示正在使用,false没有使用
        }
    }
}